package com.tianbao54.grpc.service;

import com.tianbao54.grpc.model.StreamRequest;
import com.tianbao54.grpc.model.StreamResponse;
import com.tianbao54.grpc.model.Talk;
import com.tianbao54.grpc.model.TalkServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.time.LocalDateTime;

public class GrpcClient {

    public static void main(String[] args) {

        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost",9999).usePlaintext(true).build();
        // synchronized 如果是 stream 请求，找不到调用方法
        TalkServiceGrpc.TalkServiceBlockingStub blockingStub = TalkServiceGrpc.newBlockingStub(managedChannel);
        // asynchronous
        TalkServiceGrpc.TalkServiceStub asyncStub = TalkServiceGrpc.newStub(managedChannel);

        StreamObserver<StreamRequest> streamObserver = asyncStub.biTalk(new StreamObserver<StreamResponse>() {
            @Override
            public void onNext(StreamResponse value) {
                System.out.println(value.getResponseInfo());
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("onCompleted");
            }
        });

        for (int i = 0 ; i < 10 ; i ++) {
            streamObserver.onNext(StreamRequest.newBuilder().setRequestInfo(LocalDateTime.now().toString()).build());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
